package com.ycx.ycxmybatismanagement.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;  
import org.springframework.stereotype.Component;  
import org.springframework.web.multipart.MultipartFile;  
  
import java.io.IOException;  
  
@Component  
public class QiniuUploadUtils {  
  
    // 替换为你的AccessKey和SecretKey  
    private static final String ACCESS_KEY = "b0BRICpf_HwT8INVKXmmOdLippyXG5J94xYr2zMu";
    private static final String SECRET_KEY = "HNDYo16MxcHDKcm5Nw_F72RvPThiwSrBXsySt9vX";
  
    // 替换为你的Bucket名称  
    private static final String BUCKET_NAME = "yyycccxxx";
  
    // 替换为你的文件访问域名  
    private static final String DOMAIN = "http://sdmvzv0cf.hn-bkt.clouddn.com";
  
    // 构造一个带指定Region对象的配置类  
    private UploadManager uploadManager = new UploadManager(new Configuration(Region.huanan()));
  
    // 获取上传凭证  
    private String getUpToken() {  
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);  
        return auth.uploadToken(BUCKET_NAME);  
    }  
  
    // 上传文件到七牛云  
    public String uploadFileToQiniu(MultipartFile file) throws IOException, QiniuException {  
        if (file.isEmpty()) {  
            throw new IllegalArgumentException("File is empty.");  
        }  
  
        String fileName = file.getOriginalFilename();  
        byte[] fileBytes = file.getBytes();  
  
        // 你可以根据需要添加文件名处理逻辑，比如添加日期前缀或UUID后缀  
  
        String upToken = getUpToken();  
        try {  
            Response response = uploadManager.put(fileBytes, fileName, upToken);  
            // 解析上传成功的结果  
            if (response.isOK()) {  
                // 返回文件访问URL  
                return DOMAIN + "/" + fileName;  
            } else {  
                // 上传失败，返回错误信息  
                return null;  
            }  
        } catch (QiniuException ex) {  
            // 处理七牛云SDK抛出的异常  
            Response r = ex.response;  
            return r.toString();  
        }  
    }  
}